import tkinter as tk
from tkinter import ttk
import time
from tkinter import filedialog
from tkcalendar import DateEntry


class CustomDialog(tk.Toplevel):
    def __init__(self, parent, title=None, message=None):
        super().__init__(parent)
        self.transient(parent)
        self.title(title)
        self.parent = parent
        self.result = None

        # 设置窗口体
        body = tk.Frame(self)
        self.initial_focus = self.body(body, message)
        body.pack(padx=5, pady=5)

        # 添加按钮
        self.buttonbox()

        self.grab_set()
        if not self.initial_focus:
            self.initial_focus = self
        self.protocol("WM_DELETE_WINDOW", self.cancel)
        self.center_to_parent()

        self.initial_focus.focus_set()
        self.wait_window(self)

    def body(self, master, message):
        # 创建消息文本
        label = tk.Label(master, text=message)
        label.pack(padx=5, pady=5)

    def buttonbox(self):
        box = tk.Frame(self)

        ok_button = tk.Button(
            box, text="OK", width=10, command=self.ok, default=tk.ACTIVE
        )
        ok_button.pack(side=tk.LEFT, padx=5, pady=5)

        self.bind("<Return>", self.ok)
        self.bind("<Escape>", self.cancel)

        box.pack()

    def ok(self, event=None):
        self.withdraw()
        self.update_idletasks()
        self.apply()
        self.cancel()

    def apply(self):
        self.result = True  # 或者其他逻辑

    def cancel(self, event=None):
        self.parent.focus_set()
        self.destroy()

    def center_to_parent(self):
        self.update_idletasks()  # 确保获得最新的信息
        parent_x = self.parent.winfo_x()
        parent_y = self.parent.winfo_y()
        parent_width = self.parent.winfo_width()
        parent_height = self.parent.winfo_height()

        width = self.winfo_reqwidth()
        height = self.winfo_reqheight()

        x = parent_x + (parent_width // 2) - (width // 2)
        y = parent_y + (parent_height // 2) - (height // 2)

        self.geometry("+{}+{}".format(x, y))


def showinfo():
    CustomDialog(app, title="", message="无所需数据")


def start_download():
    max_steps = 100
    for i in range(max_steps + 1):
        time.sleep(0.05)  # 模拟下载延迟
        progress_var.set(i)  # 更新进度条的值
        app.update_idletasks()  # 刷新UI
    print("Download complete!")


def browse_folder():
    # 打开目录选择对话框
    directory_path = filedialog.askdirectory()
    if directory_path:
        print(f"Selected directory: {directory_path}")
    # 再次显示主窗口
    app.deiconify()
    output_path_var.set(directory_path)


def visualize_analysis():
    pass


app = tk.Tk()
app.title("IERS数据下载助手")

# Row 1
frame = ttk.Frame(app, padding="3")
frame.grid(row=0, column=0, sticky=(tk.W, tk.E))
ttk.Label(frame, text="选择爬取日期范围:").pack(side=tk.LEFT)
start_date = DateEntry(frame, year=2024, month=5, day=1, date_pattern="y-mm-dd")
start_date.pack(side=tk.LEFT)
end_date = DateEntry(frame, year=2024, month=5, day=3, date_pattern="y-mm-dd")
end_date.pack(side=tk.LEFT)
ttk.Label(frame, text="选择数据类型:").pack(side=tk.LEFT)
data_type_choices = ["类型A", "类型B", "类型C"]
var = tk.StringVar()
data_type = ttk.Combobox(frame, values=data_type_choices, width=10, textvariable=var)
data_type.pack(side=tk.LEFT)
var.set(data_type_choices[1])
ttk.Label(frame, text="  自动更新天数:").pack(side=tk.LEFT)
update_days_choices = ["1天", "4天", "7天", "15天"]
update_days = ttk.Combobox(frame, values=update_days_choices, width=10)
update_days.pack(side=tk.LEFT)

# Row 2: File path and action buttons
frame = ttk.Frame(app, padding="3")
frame.grid(row=1, column=0, sticky=(tk.W, tk.E))
ttk.Label(frame, text="文件保存路径:").pack(side=tk.LEFT)
output_path_var = tk.StringVar()
output_path = ttk.Entry(frame, width=20, state="readonly", textvariable=output_path_var)
output_path.pack(side=tk.LEFT, padx=5)
output_path_var.set("E:IERS_download")
ttk.Button(frame, text="浏览", command=browse_folder).pack(side=tk.LEFT, padx=5)
ttk.Button(frame, text="开始下载", command=showinfo).pack(side=tk.LEFT, padx=20)
ttk.Button(frame, text="可视化分析", command=visualize_analysis).pack(
    side=tk.LEFT, padx=0
)

# Row 3: Download progress
frame = ttk.Frame(app, padding="3")
frame.grid(row=2, column=0, sticky=(tk.W, tk.E))
ttk.Label(frame, text="下载进度:").pack(side=tk.LEFT)
progress_var = tk.IntVar()
progress_bar = ttk.Progressbar(frame, maximum=100, variable=progress_var)
progress_bar.pack(side=tk.LEFT, padx=10, fill=tk.X, expand=True)


frame = ttk.Frame(app, padding="10")
frame.grid(row=3, column=0, sticky=(tk.W, tk.E))
# Table for showing the results
columns = (
    "数据类型",
    "Title",
    "Date",
    "Text File",
    "HTML File",
    "CSV File",
    "下载状态",
)
tree = ttk.Treeview(frame, columns=columns, show="headings")
tree.pack(expand=True, fill=tk.BOTH)
for col in columns:
    tree.heading(col, text=col.capitalize())
    tree.column(col, width=100)
app.mainloop()
